import 'dart:async';
import 'dart:math';

import 'package:audio_session/audio_session.dart';
import 'package:chat_app_project/tool/time.dart';
import 'package:chat_app_project/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:wukongimfluttersdk/model/wk_voice_content.dart';
import 'package:wukongimfluttersdk/type/const.dart';

import '../../../const/sys_const.dart';
import '../../../constants.dart';
import '../../../models/const.dart';
import '../../../models/msg.dart';

class AudioMessage extends StatefulWidget {
  AudioMessage({super.key, required this.message});

  final UIMsg message;

  @override
  State<AudioMessage> createState() => _AudioMessageState();
}

class _AudioMessageState extends State<AudioMessage> {
  final _player = AudioPlayer(
    // Handle audio_session events ourselves for the purpose of this demo.
    handleInterruptions: false,
    androidApplyAudioAttributes: false,
    handleAudioSessionActivation: false,
  );
  play(url) {
    stop();
    AudioSession.instance.then((audioSession) async {
      // This line configures the app's audio session, indicating to the OS the
      // type of audio we intend to play. Using the "speech" recipe rather than
      // "music" since we are playing a podcast.
      await audioSession.configure(const AudioSessionConfiguration.speech());
      // Listen to audio interruptions and pause or duck as appropriate.
      _handleInterruptions(audioSession);
      // Use another plugin to load audio to play.
      // "https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3"
      await _player.setUrl(url);
      //播放 设置状态
      _player.play();
      setState(() {});
    });
  }

  stop() {
    _player.stop();
  }

  int playTime = 0;
  initTimer(int maxTime) {
    playTime = 0;
    Timer.periodic(const Duration(seconds: 1), (Timer timer) async {
      playTime++;
      debugPrint("计时 $playTime  max $maxTime  播放状态 ${_player.playing}");
      // if (!_player.playing) {
      //   timer.cancel();
      // }
      if (playTime > maxTime) {
        debugPrint("计时结束");
        timer.cancel();
        stop();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    _player.dispose();
  }
  //监听打断信息
  void _handleInterruptions(AudioSession audioSession) {
    // just_audio can handle interruptions for us, but we have disabled that in
    // order to demonstrate manual configuration.
    bool playInterrupted = false;
    audioSession.becomingNoisyEventStream.listen((_) {
      print('PAUSE');
      _player.pause();
    });
    _player.playingStream.listen((playing) {
      playInterrupted = false;
      if (playing) {
        audioSession.setActive(true);
      }
    });
    audioSession.interruptionEventStream.listen((event) {
      print('interruption begin: ${event.begin}');
      print('interruption type: ${event.type}');
      if (event.begin) {
        switch (event.type) {
          case AudioInterruptionType.duck:
            if (audioSession.androidAudioAttributes!.usage ==
                AndroidAudioUsage.game) {
              _player.setVolume(_player.volume / 2);
            }
            playInterrupted = false;
            break;
          case AudioInterruptionType.pause:
          case AudioInterruptionType.unknown:
            if (_player.playing) {
              _player.pause();
              playInterrupted = true;
            }
            break;
        }
      } else {
        switch (event.type) {
          case AudioInterruptionType.duck:
            _player.setVolume(min(1.0, _player.volume * 2));
            playInterrupted = false;
            break;
          case AudioInterruptionType.pause:
            if (playInterrupted) _player.play();
            playInterrupted = false;
            break;
          case AudioInterruptionType.unknown:
            playInterrupted = false;
            break;
        }
      }
    });
    audioSession.devicesChangedEventStream.listen((event) {
      print('Devices added: ${event.devicesAdded}');
      print('Devices removed: ${event.devicesRemoved}');
    });
  }

  @override
  Widget build(BuildContext context) {
    var wkMsg = widget.message.wkMsg;
    var content = wkMsg.messageContent as WKVoiceContent;
    var isSender = wkMsg.fromUID == UserInfo.uid;

    return GestureDetector(
      onTap: () {
        if (wkMsg.status == WKSendMsgResult.sendSuccess) {
          if (!_player.playing) {
            play(content.url);
            initTimer(content.timeTrad);
          } else {
            stop();
            setState(() {});
          }
          return;
        }
        ToastUtil.toast("发送失败!");
      },
      child: Container(
        width: MediaQuery.of(context).size.width * 0.55,
        padding: const EdgeInsets.symmetric(
          horizontal: kDefaultPadding * 0.75,
          vertical: kDefaultPadding / 2.5,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(30),
          color: kPrimaryColor.withOpacity(isSender ? 1 : 0.1),
        ),
        child: Row(
          children: [
            Icon(_player.playing ? Icons.stop : Icons.play_arrow,
                color: isSender ? Colors.white : kPrimaryColor),
            Expanded(
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: kDefaultPadding / 2),
                child: Stack(
                  clipBehavior: Clip.none,
                  alignment: Alignment.center,
                  children: [
                    Container(
                      width: double.infinity,
                      height: 2,
                      color: isSender
                          ? Colors.white
                          : kPrimaryColor.withOpacity(0.4),
                    ),
                    Positioned(
                      left: 0,
                      child: Container(
                        height: 8,
                        width: 8,
                        decoration: BoxDecoration(
                          color: isSender
                              ? Colors.white
                              : kPrimaryColor.withOpacity(0.4),
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Text(
                TimeUtils.getHMmmss_Seconds(
                    _player.playing ? playTime : content.timeTrad),
                style: TextStyle(
                    fontSize: 12, color: isSender ? Colors.white : null))
          ],
        ),
      ),
    );
  }
}
